#include <iostream>
#include <string>
#include <fcntl.h>
#include <sys/stat.h>
#include <mqueue.h>
#include <signal.h>
#include <errno.h>

const char* POSIX_QUEUE_NAME="/HBTY_MSGQUEUE_PROJECT";

mqd_t queue_key;
long msgSize;

void Handle_SIGINT(int)
{
  mq_close(queue_key);
  mq_unlink(POSIX_QUEUE_NAME);
  std::cout<<"Client Exit, Bye bye!"<<std::endl;
  exit(0);
}

int main()
{
  signal(SIGINT,Handle_SIGINT);
  queue_key=mq_open(POSIX_QUEUE_NAME,O_EXCL | O_RDWR);
  if(queue_key==-1)
  {
    std::cout<<"Can't open queue :"<<errno<<std::endl;
    return -1;
  }
  struct mq_attr attr;
  if(mq_getattr(queue_key,&attr)==-1)
  {
    std::cout<<"Can't get queue attr"<<std::endl;
    return -1;
  }
  else
    std::cout<<"Queue message size : "<<attr.mq_msgsize<<std::endl;
  msgSize=attr.mq_msgsize;
  
  std::string sendMsg;
  char* receiveBuffer=new char[msgSize];
  
  while(true)
  {
    std::cout<<"Send Msg >> ";
    std::getline(std::cin,sendMsg);
    if(mq_send(queue_key,sendMsg.c_str(),sendMsg.length()+1,0)==-1)
    {
      std::cout<<"Msg Send Failed"<<std::endl;
      continue;
    }
    ssize_t recSize=mq_receive(queue_key,receiveBuffer,msgSize,nullptr);
    if(recSize==-1)
    {
      std::cout<<"Receive message failed"<<std::endl;
      continue;
    }
    std::cout<<"Receive Msg << "<<receiveBuffer<<std::endl;
  }
}
